{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2d39ae18",
   "metadata": {},
   "source": [
    "# 调用手机摄像头，逐帧实时拍摄+OpenCV图像处理\n",
    "\n",
    "同济子豪兄 2023-6-25"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b1583e5",
   "metadata": {},
   "source": [
    "## 导入工具包"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8de9bb2a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "import cv2\n",
    "\n",
    "from cvs import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54e2de95",
   "metadata": {},
   "source": [
    "## 初始化摄像头"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "81067a1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 摄像头ID 0-后置 1-前置\n",
    "Camera_ID = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1fd0fe7f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "remi.server      INFO     Started httpserver http://0.0.0.0:60194/\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('app runs on port:', 60194)\n",
      "open the cam:0 ...\n"
     ]
    }
   ],
   "source": [
    "cap = cvs.VideoCapture(Camera_ID)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45bbd9b3",
   "metadata": {},
   "source": [
    "## 逐帧处理函数（选择一个运行）\n",
    "\n",
    "逐帧处理函数，默认不进行任何处理，直接将摄像头捕获的画面写入视频帧"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7b5ff3fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 什么都不做\n",
    "def process_frame(img_bgr):\n",
    "    '''输入BGR格式的 numpy array，输出BGR格式的 numpy array'''\n",
    "    # img_bgr = img_bgr[:,:,::-1] # BGR转RGB\n",
    "    return img_bgr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3a5e8207",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "remi.server.ws   INFO     connection established: ('127.0.0.1', 37590)\n",
      "remi.server.ws   INFO     handshake complete\n"
     ]
    }
   ],
   "source": [
    "# Canny 边缘检测\n",
    "def process_frame(img_bgr):\n",
    "    '''输入BGR格式的 numpy array，输出BGR格式的 numpy array'''\n",
    "    img_bgr = cv2.Canny(img_bgr, 100, 200)\n",
    "    img_bgr = np.dstack((img_bgr, img_bgr, img_bgr))\n",
    "    return img_bgr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4e0d4288",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Canny 边缘检测 - 写 FPS 数值\n",
    "def process_frame(img_bgr):\n",
    "    '''输入BGR格式的 numpy array，输出BGR格式的 numpy array'''\n",
    "    \n",
    "    # 记录该帧开始处理的时间\n",
    "    start_time = time.time()\n",
    "    \n",
    "    # 逐帧处理操作\n",
    "    img_bgr = cv2.Canny(img_bgr, 100, 200)\n",
    "    img_bgr = np.dstack((img_bgr, img_bgr, img_bgr))\n",
    "    \n",
    "    # 记录该帧处理完毕的时间\n",
    "    end_time = time.time()\n",
    "    # 计算每秒处理图像帧数FPS\n",
    "    FPS = 1/(end_time - start_time)\n",
    "\n",
    "    # 在画面上写 FPS 数值\n",
    "    end_time = time.time()\n",
    "    FPS = 1/(end_time - start_time) # 计算每秒处理图像帧数FPS\n",
    "    FPS_string = 'FPS {:.2f}'.format(FPS) # 写在画面上的字符串\n",
    "    img_bgr = cv2.putText(img_bgr, FPS_string, (25, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (255, 0, 255), 2) # 在画面上写字：图片，字符串，左上角坐标，字体，字体大小，颜色，字体粗细\n",
    "\n",
    "    return img_bgr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "78ae54ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Hough 直线检测 - 写 FPS 数值\n",
    "def process_frame(img_bgr):\n",
    "    \n",
    "    # 记录该帧开始处理的时间\n",
    "    start_time = time.time()\n",
    "    \n",
    "    img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # BGR 转 灰度图\n",
    "    edges = cv2.Canny(img_gray, 50, 150, apertureSize=3) # Canny 直线检测\n",
    "    lines = cv2.HoughLines(edges, 1, np.pi / 180, 150)   # 霍夫直线检测\n",
    "    \n",
    "    if lines is None: # 如果检测出直线\n",
    "        pass\n",
    "    else:\n",
    "        for line in lines:\n",
    "            rho, theta = line[0]\n",
    "            a = np.cos(theta)\n",
    "            b = np.sin(theta)\n",
    "            x0 = a * rho\n",
    "            y0 = b * rho\n",
    "            # x1 stores the rounded off value of (r * cos(theta) - 1000 * sin(theta))\n",
    "            x1 = int(x0 + 1000 * (-b))\n",
    "            # y1 stores the rounded off value of (r * sin(theta)+ 1000 * cos(theta))\n",
    "            y1 = int(y0 + 1000 * (a))\n",
    "            # x2 stores the rounded off value of (r * cos(theta)+ 1000 * sin(theta))\n",
    "            x2 = int(x0 - 1000 * (-b))\n",
    "            # y2 stores the rounded off value of (r * sin(theta)- 1000 * cos(theta))\n",
    "            y2 = int(y0 - 1000 * (a))\n",
    "            img_bgr = cv2.line(img_bgr, (x1, y1), (x2, y2), (0, 0, 255), 2)\n",
    "    \n",
    "    # 在画面上写 FPS 数值\n",
    "    end_time = time.time()\n",
    "    FPS = 1/(end_time - start_time) # 计算每秒处理图像帧数FPS\n",
    "    FPS_string = 'FPS {:.2f}'.format(FPS) # 写在画面上的字符串\n",
    "    img_bgr = cv2.putText(img_bgr, FPS_string, (25, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (255, 0, 255), 2) # 在画面上写字：图片，字符串，左上角坐标，字体，字体大小，颜色，字体粗细\n",
    "    \n",
    "    return img_bgr"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4bee659",
   "metadata": {},
   "source": [
    "## 逐帧实时处理手机摄像头拍摄的画面-代码模板"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "672bc337",
   "metadata": {},
   "outputs": [],
   "source": [
    "while True:\n",
    "    img_bgr = cap.read()\n",
    "    \n",
    "    if img_bgr is None:\n",
    "        continue\n",
    "        \n",
    "    img_bgr = process_frame(img_bgr)\n",
    "    \n",
    "    cvs.imshow(img_bgr)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8c6c8dc",
   "metadata": {},
   "source": [
    "## 点击`重启kernel`关闭摄像头"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74419ea6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
